package com.travel.service.impl.Service;

import com.travel.exception.ResourceNotFoundException;
import com.travel.exception.UnauthorizedException;
import com.travel.mapper.content.CommentMapper;
import com.travel.mapper.service.ServiceMapper;
import com.travel.mapper.user.UserMapper;
import com.travel.model.dto.comment.CommentRequest;
import com.travel.model.dto.comment.RatingStats;
import com.travel.model.entity.content.Comment;
import com.travel.model.entity.service.Service;
import com.travel.service.Service.ServiceService;
import com.travel.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
//服务服务实现类 获取所有服务 获取特定城市服务 获取特定服务 创建服务 更新服务 删除服务 搜索服务 添加评论 获取评论 获取评分统计
@org.springframework.stereotype.Service
@RequiredArgsConstructor
public class ServiceServiceImpl implements ServiceService {
    
    private final ServiceMapper serviceMapper;
    private final CommentMapper commentMapper;
    private final UserMapper userMapper;
    
    // ... 其他现有方法
    
    @Override
    @Transactional
    public Comment addComment(Long serviceId, CommentRequest request) {
        // 检查服务是否存在
        Service service = serviceMapper.findById(serviceId)
            .orElseThrow(() -> new ResourceNotFoundException("服务不存在"));
            
        Comment comment = new Comment();
        comment.setContent(request.getContent());
        comment.setRating(request.getRating());
        comment.setUserId(SecurityUtils.getCurrentUserId());
        comment.setTargetId(serviceId);
        comment.setTargetType(Comment.TargetType.SERVICE);
        comment.setCreatedTime(LocalDateTime.now());
        comment.setStatus(1);
        
        commentMapper.insert(comment);
        return comment;
    }
    
    @Override
    @Transactional
    public void deleteComment(Long commentId, Long userId) {
        Comment comment = commentMapper.findById(commentId)
            .orElseThrow(() -> new ResourceNotFoundException("评论不存在"));
            
        if (!comment.getUserId().equals(userId)) {
            throw new UnauthorizedException("您没有权限删除此评论");
        }
        
        comment.setStatus(0);
        commentMapper.update(comment);
    }
    
    @Override
    public RatingStats getServiceRating(Long serviceId) {
        RatingStats stats = new RatingStats();
        stats.setAverageRating(commentMapper.getAverageRating(
            serviceId, Comment.TargetType.SERVICE));
        stats.setCommentCount(commentMapper.getCommentCount(
            serviceId, Comment.TargetType.SERVICE));
        return stats;
    }
} 